import pandas as pd
from datetime import datetime

from rectify.error1 import get_age_from_idcard


def error4_idf(df,dict_info_setting, columns):
    """
    检查随访分类为'控制满意'时，血压和血糖是否符合标准，并生成样式和批注信息。

    :param df: 数据 DataFrame
    :param columns: 涉及的列名列表，顺序为 ['空腹血糖(mmol/L)', '此次随访分类', '收缩压(mmHg)', '舒张压(mmHg)', '身份证号']
    :return: (styles_info, comments_info) 样式和批注信息
    """
    styles_info = {}
    comments_info = []

    xuetang = float(dict_info_setting["error4_idf"].split(":")[-1])


    # 解析列名
    blood_glucose_col, category_col, systolic_col, diastolic_col, id_col = columns

    for row_idx, row in df.iterrows():
        try:
            # 只处理随访分类为'控制满意'的行
            if row[category_col] != '控制满意':
                continue

            # 获取身份证和年龄
            id_card = str(row[id_col]).strip()
            age = get_age_from_idcard(id_card)

            # ---- 检查血压是否符合标准 ----
            systolic = row[systolic_col]
            diastolic = row[diastolic_col]

            # 转换为数值类型
            try:
                systolic = float(systolic)
                diastolic = float(diastolic)
            except ValueError:
                continue  # 跳过无效值

            # 根据年龄判断血压标准
            bp_qualified = False
            if age < 65:
                if systolic < 140 and diastolic < 90:
                    bp_qualified = True
            else:
                if systolic < 150 and diastolic < 90:
                    bp_qualified = True

            # # 如果血压不达标
            # if not bp_qualified:
            #     # 标记相关列为红色
            #     for col in [category_col, systolic_col, diastolic_col]:
            #         styles_info[(row_idx, col)] = 'error'
            #
            #     # 生成批注信息
            #     if age < 65:
            #         msg = f"血压控制不达标（收缩压 {systolic}≥140mmHg 或舒张压 {diastolic}≥90mmHg），但随访分类为'控制满意'。请核实。"
            #     else:
            #         msg = f"血压控制不达标（收缩压 {systolic}≥150mmHg 或舒张压 {diastolic}≥90mmHg），但随访分类为'控制满意'。请核实。"
            #
            #     # 将批注添加到随访分类列
            #     comments_info.append((row_idx, category_col, msg))

            # ---- 检查血糖是否符合标准 ----
            blood_glucose = row[blood_glucose_col]

            try:
                blood_glucose = float(blood_glucose)
            except ValueError:
                continue  # 跳过无效值

            # 血糖标准（所有年龄均 <7.0）
            if blood_glucose >= xuetang:
                # 标记相关列为红色
                for col in [blood_glucose_col, category_col]:
                    styles_info[(row_idx, col)] = 'error'

                # 生成批注信息
                msg = f"空腹血糖 {blood_glucose}≥{xuetang}mmol/L，但随访分类为'控制满意'。请核实。"
                comments_info.append((row_idx, category_col, msg))

        except Exception as e:
            print(f"第 {row_idx + 2} 行处理出错: {str(e)}")
            continue

    return styles_info, comments_info

